package com.zhanghe.study.sqlsession;

import com.zhanghe.study.config.Function;
import com.zhanghe.study.config.MapperBean;
import com.zhanghe.study.config.MyConfig;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 代理类完成xml方法和真实方法的对应，执行查询
 */
public class MyMapperProxy implements InvocationHandler {
    private MySqlSession mySqlSession;

    private MyConfig myConfig;

    public MyMapperProxy(MySqlSession sqlSession, MyConfig config) {
        this.mySqlSession = sqlSession;
        this.myConfig = config;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        MapperBean mapperBean = myConfig.readMapper("UserMapper.xml");
        if (!method.getDeclaringClass().getName().equals(mapperBean.getInterfaceName())) {
            return null;
        }
        List<Function> list = mapperBean.getList();
        if (list != null && list.size() > 0) {
            for(Function function : list){
                if(function.getMethodName().equals(method.getName())){
                    return mySqlSession.selectOne(function.getSql(),String.valueOf(args[0]));
                }
            }
        }
        return null;
    }
}
